package eos.dom;

import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class DomChooseCardsPopup extends Activity {

	private Vector<String> cards;
	private TextView text;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.choosecardspopuplayout);
		text = (TextView)findViewById(R.id.ChooseCardText);

		ListView l = (ListView)findViewById(R.id.CardList);
		l.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		cards= new Vector<String>();
		for(int i=CardId.CELLAR.ordinal();i<=CardId.ADVENTURER.ordinal();i++){
			cards.add(CardId.values()[i].toString());
		}
		ArrayAdapter<Object> cardList = new ArrayAdapter<Object>(this,
				android.R.layout.simple_list_item_multiple_choice, cards.toArray());
		l.setAdapter(cardList);
		
		Button validate = (Button)findViewById(R.id.ChooseCardValidate);
		validate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ListView l = (ListView)findViewById(R.id.CardList);
				SparseBooleanArray checked = l.getCheckedItemPositions();
				int checkedNumber = 0;
				for(int i = 0;i<l.getAdapter().getCount();i++){
					if(checked.get(i)){
						checkedNumber++;
					}
				}
				String s = "Nb ="+checkedNumber+"\n";
				DomStart.cardsChosen = new int[checkedNumber];
				int idx= 0;
				for(int i = 0;i<l.getAdapter().getCount();i++){
					if(checked.get(i)){
						s += CardId.valueOf(cards.get(i)).ordinal();
						idx++;
					}
				}
				text.setText(s);
			}
		});
	}
	
	@Override
	public void onBackPressed() {
		if(onQuit()){
			finish();
		}
	}

	protected boolean onQuit() {
		ListView l = (ListView)findViewById(R.id.CardList);
		SparseBooleanArray checked = l.getCheckedItemPositions();
		int checkedNumber = 0;
		for(int i = 0;i<l.getAdapter().getCount();i++){
			if(checked.get(i)){
				checkedNumber++;
			}
		}
		
		if(checkedNumber > 10){
			new AlertDialog.Builder(this)
		      .setMessage("Too many cards selected")
		      .show();
			return false;
		}else if(checkedNumber == 10){
			setResult(DomStart.CARDS_CHOSEN_ENOUGH);
		}else if(checkedNumber >= 0){
			setResult(DomStart.CARDS_CHOSEN_NOT_ENOUGH);
		}
		
		DomStart.cardsChosen = new int[checkedNumber];
		int idx= 0;
		for(int i = 0;i<l.getAdapter().getCount();i++){
			if(checked.get(i)){
				DomStart.cardsChosen[idx] = CardId.valueOf(cards.get(i)).ordinal();
				idx++;
			}
		}
		return true;
	}

}
